package com.laiketui.app.controller;

import com.laiketui.app.api.IndexService;
import com.laiketui.common.api.PublicGoodsService;
import com.laiketui.core.annotation.ParamsMapping;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.common.SplitUtils;
import com.laiketui.core.domain.Result;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.tool.DataUtils;
import com.laiketui.domain.config.GuideModel;
import com.laiketui.domain.vo.MainVo;
import com.laiketui.root.annotation.HttpApiMethod;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 小程序首页
 *
 * @author Trick
 * @date 2020/10/10 9:01
 */
@Api(tags = "商城首页")
@RestController
@Validated
public class IndexController {

    @Autowired
    IndexService indexService;

    @Autowired
    private PublicGoodsService publicGoodsService;

    @Autowired
    RedisUtil redisUtil;

    @ApiOperation("首页是否div接口")
    @PostMapping("hasDiy")
    @HttpApiMethod(urlMapping = "app.index.hasDiy")
    public Result hasDiy(MainVo vo) {
        try {
            return Result.success(indexService.hasDiy(vo.getStoreId()));
        } catch (LaiKeAPIException e) {
            return Result.error(e.getCode(), e.getMessage());
        }
    }

    @ApiOperation("插件状态")
    @PostMapping("pluginStatus")
    @HttpApiMethod(urlMapping = "app.index.pluginStatus")
    public Result pluginStatus(MainVo vo, Integer mchId) {
        try {
            return Result.success(indexService.pluginStatus(vo, mchId));
        } catch (LaiKeAPIException e) {
            return Result.error(e.getCode(), e.getMessage());
        }
    }

    @ApiOperation("首页接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "商城id", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "accessId", value = "授权id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "storeType", value = "来源", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "language", value = "语言", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "latitude", value = "纬度", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "longitude", value = "经度", required = true, dataType = "String", paramType = "form")
    })
    @PostMapping("index")
    @HttpApiMethod(urlMapping = {"app.index.index"})
    public Result index(@NotNull @ParamsMapping({"store_id"}) int storeId, @ParamsMapping("access_id") String accessId,
                        @NotNull @ParamsMapping("store_type") String storeType,
                        String language, @NotNull String longitude, @NotNull String latitude) {
        try {
            //商城首页缓存key 如果该缓存不存在则强制刷新用户相应的首页缓存
            String redisIndexCacheKey = String.format(GloabConst.RedisHeaderKey.JAVA_INDEX_CACHE, storeId);
            Object indexData = null;
            Map<String, Object> resultJson = null;
            //是否重新获取数据并刷新缓存标识
            boolean isReloadData = true;

            //当前用户数据标识key
            StringBuilder thisStr = new StringBuilder(storeId).append(SplitUtils.DH).append(accessId)
                    .append(SplitUtils.DH).append(storeType).append(SplitUtils.DH).append(language)
                    .append(SplitUtils.DH).append(longitude).append(SplitUtils.DH).append(latitude);
            //首页数据缓存处理-当前用户
            String indexCacheCondition = String.format(GloabConst.RedisHeaderKey.INDEX_CACHE_CONDITION_, storeId, accessId);

            if (redisUtil.hasKey(redisIndexCacheKey)) {
                String str = "";
                if (redisUtil.hasKey(indexCacheCondition)) {
                    //读取当前用户缓存
                    str = redisUtil.get(indexCacheCondition).toString();
                    //直接读取缓存数据
                    if (thisStr.toString().equals(str)) {
                        indexData = redisUtil.get(redisIndexCacheKey);
                        resultJson = DataUtils.cast(indexData);
                    }
                }
                //重新获取数据
//                isReloadData = indexData == null;
            }

            if (isReloadData) {
                //重新读取数据
                resultJson = indexService.index(storeId, accessId, storeType, language, longitude, latitude);
                redisUtil.set(indexCacheCondition, thisStr, 300);
                redisUtil.set(redisIndexCacheKey, resultJson, 300);
            }
            return Result.success(resultJson);
        } catch (LaiKeAPIException e) {
            return Result.error(e.getCode(), e.getMessage());
        }
    }



//    @ApiOperation("获取用户是否是会员")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "storeId", value = "商城id", required = true, dataType = "int", paramType = "form")
//    })
//    @PostMapping("getUserGradeRate")
//    @HttpApiMethod(urlMapping = "app.index.get_membership_status")
//    public Result getUserGradeRate(@NotNull @ParamsMapping("store_id") int storeId) {
//        try {
//            Map<String, Object> resultJson = indexService.getMembershipStatus(storeId);
//            return Result.success(resultJson);
//        } catch (LaiKeAPIException e) {
//            return Result.error(e.getCode(), e.getMessage());
//        }
//    }

    @ApiOperation("加载更多商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cid", value = "分类id", required = true, dataType = "int", paramType = "form")
    })
    @PostMapping("get_more")
    @HttpApiMethod(urlMapping = "app.index.get_more")
    public Result getMore(MainVo vo, int cid) {
        try {
            List<Map<String, Object>> resultJson = indexService.getMore(vo, cid);
            return Result.success(resultJson);
        } catch (LaiKeAPIException e) {
            return Result.error(e.getCode(), e.getMessage());
        }
    }

    @ApiOperation("获取地理位置")
    @PostMapping("get_location")
    @HttpApiMethod(urlMapping = {"app.index.get_location", "app.index.get_Longitude_and_latitude"})
    public Result getLocation(MainVo vo, @ParamsMapping("GroupID") Integer groupId) {
        try {
            Map<String, Object> resultJson = indexService.getLocation(vo, groupId);
            return Result.success(resultJson);
        } catch (LaiKeAPIException e) {
            return Result.error(e.getCode(), e.getMessage());
        }
    }

    @ApiOperation("获取引导图api")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "store_id", value = "商城id", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "access_id", value = "授权id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "language", value = "语言", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "store_type", value = "来源", required = true, dataType = "int", paramType = "form")
    })
    @PostMapping("guided_graph")
    @HttpApiMethod(urlMapping = "app.index.guided_graph")
    public Result guidedGraph(@RequestParam("store_id") int storeId, @RequestParam("access_id") String accessId,
                              String language, @RequestParam("guideType") int guideType) {
        try {
            List<GuideModel> result = indexService.guidedGraph(storeId, accessId, language, guideType);
            return Result.success(result);
        } catch (LaiKeAPIException e) {
            return Result.error(e.getCode(), e.getMessage());
        }
    }

    @ApiOperation("新品上市")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "store_id", value = "商城id", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "access_id", value = "授权id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "language", value = "语言", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "page", value = "分页", required = true, dataType = "int", paramType = "form")
    })
    @PostMapping("new_arrival")
    @HttpApiMethod(urlMapping = "app.index.new_arrival")
    public Result newArrival(MainVo vo) {
        try {
            Map<String, Object> result = indexService.newArrival(vo);
            return Result.success(result);
        } catch (LaiKeAPIException e) {
            return Result.error(e.getCode(), e.getMessage());
        }
    }

    @ApiOperation("(优选店铺)推荐门店api")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "longitude", value = "经度", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "latitude", value = "维度", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "cid", value = "店铺分类id", required = true, dataType = "int", paramType = "form"),
    })
    @PostMapping("recommend_stores")
    @HttpApiMethod(urlMapping = "app.index.recommend_stores")
    public Result recommendStores(MainVo vo, @NotNull String longitude, @NotNull String latitude, Integer cid) {
        try {
            Map<String, Object> result = indexService.recommendStores(vo, longitude, latitude, cid);
            return Result.success(result);
        } catch (LaiKeAPIException e) {
            return Result.error(e.getCode(), e.getMessage());
        }
    }

    @ApiOperation("店铺分类")
    @PostMapping("mchClass")
    @HttpApiMethod(urlMapping = {"app.index.mchClass", "mch.mall.Mch.mchClass"})
    public Result mchClass(MainVo vo) {
        try {
            return Result.success(indexService.mchClass(vo));
        } catch (LaiKeAPIException e) {
            return Result.error(e.getCode(), e.getMessage());
        }
    }

    @ApiOperation("更改语言api")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "store_id", value = "商城id", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "access_id", value = "授权id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "language", value = "语言", required = true, dataType = "String", paramType = "form")
    })
    @PostMapping("select_language")
    @HttpApiMethod(urlMapping = "app.index.select_language")
    public Result selectLanguage(@RequestParam("store_id") @NotNull int storeId, @RequestParam("access_id") @NotNull String accessId, @NotNull String language) {
        try {
            boolean result = indexService.selectLanguage(storeId, accessId, language);
            if (result) {
                return Result.success("Success");
            } else {
                return Result.error("Fail");
            }
        } catch (LaiKeAPIException e) {
            return Result.error(e.getCode(), e.getMessage());
        }
    }

    @ApiOperation("推荐商品api(好物优选)")
    @PostMapping("recommend")
    @HttpApiMethod(urlMapping = "app.index.recommend")
    public Result recommend(MainVo vo) {
        try {
            return Result.success(indexService.recommend(vo));
        } catch (LaiKeAPIException e) {
            return Result.error(e.getCode(), e.getMessage());
        }
    }

    @ApiOperation("获取平台用户公告")
    @PostMapping("getUserTell")
    @HttpApiMethod(urlMapping = "app.index.getUserTell")
    public Result getUserTell(MainVo vo) {
        try {
            return Result.success(indexService.getUserTell(vo));
        } catch (LaiKeAPIException e) {
            return Result.error(e.getCode(), e.getMessage());
        }
    }


    @ApiOperation("标记公告以读")
    @PostMapping("/markToRead")
    @HttpApiMethod(apiKey = "app.Index.markToRead")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tell_id", value = "公告id", dataType = "int", paramType = "form")
    })
    public Result markToRead(MainVo vo, Integer tell_id) {
        try {
            indexService.markToRead(vo, tell_id);
            return Result.success(GloabConst.ManaValue.MANA_VALUE_SUCCESS);
        } catch (LaiKeAPIException e) {
            return Result.error(e.getCode(), e.getMessage());
        }
    }
}
